<?php

namespace app\merchant\controller\market;
use app\merchant\controller\Base;
use app\common\model\SettingLog as SettingLogSettingModel;
use app\factory\MqFactory;
use app\common\model\divide\Receive as ReceiveModel;

/**
 * 营销设置-分红设置
 * Class Basic
 * @package app\store\controller
 */
class Setting extends Base
{
    /**
     * 分红设置
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $nowTime = time();
        $wxapp_id = $this->getWxappId();


        $values = db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->find();
        if($values){
            $values['start_time'] = date('Y-m-d H:i:s', $values['start_time']);
        }else{
            $values['status'] = 2;//分红开关 1 开启 2关闭
            $values['start_time'] = date('Y-m-d H:i:s', $nowTime);//开始时间
            $values['money'] = 0;//分红条件
            $values['term'] = 0;//分红周期
            $values['upline'] = 0;//分红上限
            $values['rewardpercent'] = 0;//分红拨比
            $values['moneypercent'] = 0;//零钱比例
            $values['moneypercentstatus'] = 2;//零钱比例开关 1 开启 2关闭
            $values['periods_num'] = 1000;
            $values['real_reward'] = 0;//实物是否参与分红 0 否 1是
        }

        return $this->renderSuccess($values,"查询成功");

    }

    /**
     * 分红设置
     */
    public function set(){

        $param = $this->postData();

        if(!isset($param['start_time']) || empty($param['start_time'])){
            return $this->renderError([],"请选择开始时间");
        }

        if(!isset($param['term']) || isInt($param['term'])){
            return $this->renderError([],"分红周期为1-18");
        }

        if($param['term']<1 || $param['term']>180){
            return $this->renderError([],"分红周期为1-18");
        }


        if(!isset($param['money'])){
            return $this->renderError([],"请输入分红条件");
        }

        if(!isset($param['upline']) || isZeroNumeric($param['upline'])){
            return $this->renderError([],"分红上限为0-100");
        }

        if($param['upline']<0 || $param['term']>100){
            return $this->renderError([],"分红上限为0-100");
        }

        if(!isset($param['rewardpercent']) || isZeroNumeric($param['rewardpercent'])){
            return $this->renderError([],"分红拨比范围为3~50");
        }

        if($param['rewardpercent']<3 || $param['rewardpercent']>50){
            return $this->renderError([],"分红拨比范围为3~50");
        }

        if(!isset($param['moneypercent']) || isZeroNumeric($param['moneypercent'])){
            return $this->renderError([],"分红拨比范围为0~100");
        }

        if($param['moneypercent']<0 || $param['moneypercent']>100){
            return $this->renderError([],"分红拨比范围为0~100");
        }

        $wxapp_id = $this->getWxappId();
        //开始时间
        $start_time = strtotime($param['start_time']);
        $endTime =  $start_time+$this->postData('model')['term']*24*60*60;

        $is_exsit = db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->find();



        $updateDate = [
            'wxapp_id' => $wxapp_id,
            'money' => $param['money'],//分红条件
            'start_time' => $start_time,//开始时间
            'end_time' => $endTime,//结束时间
            'term' => $param['term'],//分红周期
            'upline' => $param['upline'],//分红上限
            'rewardpercent' => $param['rewardpercent'],//分红拨比
            'moneypercent' => $param['moneypercent'],//零钱比例
            'moneypercentstatus' => $param['moneypercentstatus'],//零钱比例开关 1 开启 2关闭
            'status' => $param['status'],//分红开关 1 开启 2关闭
            'real_reward' => $param['real_reward'],//实物是否参与分红 0 否 1是

        ];

        $settingLog = new SettingLogSettingModel();

        if($is_exsit){
            //以前的开始时间
            $oldStartTime = $is_exsit['start_time'];

            if($start_time!=$oldStartTime){
                //出局处理
                $rmq = MqFactory::instance();

                $data = ['wxapp_id'=>$wxapp_id,'periods_num'=>$is_exsit['periods_num']];

                $rmq->send($data,'divideReceives','divideReceivesLog','divideReceivesLog');

                $updateDate['periods_num'] = $is_exsit['periods_num']+1;
            }else{
                $updateDate['periods_num'] = $is_exsit['periods_num'];
            }

            db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->update($updateDate);

            //设备类型
            $deviceType = getDeviceType();
            //写入分红配置日志 start
            $logData = [
                'type'=>1,//1：分红设置  2：会员卡分红设置
                'create_time'=>time(),
                'client'=>"分红设置",
                'deviceType'=>$deviceType,
                'wxapp_id'=>$wxapp_id
            ];
            $settingLog->addData($logData,$updateDate);

        }else{
            $insertData = [
                'wxapp_id' => $wxapp_id,
                'money' => $param['money'],//分红条件
                'start_time' => $start_time,//开始时间
                'end_time' => $endTime,//结束时间
                'term' => $param['term'],//分红周期
                'upline' => $param['upline'],//分红上限
                'rewardpercent' => $param['rewardpercent'],//分红拨比
                'moneypercent' => $param['moneypercent'],//零钱比例
                'moneypercentstatus' => $param['moneypercentstatus'],//零钱比例开关 1 开启 2关闭
                'status' => $param['status'],//分红开关 1 开启 2关闭
                'real_reward' => $param['real_reward'],//实物是否参与分红 0 否 1是
                'periods_num' => 1000,
            ];


            //设备类型
            $deviceType = getDeviceType();
            //写入分红配置日志 start
            $logData=[
                'type'=>1,//1：分红设置  2：会员卡分红设置
                'create_time'=>time(),
                'client'=>"分红设置",
                'deviceType'=>$deviceType,
                'wxapp_id'=>$wxapp_id
            ];
            $settingLog->addData($logData,$insertData);

            db('wxapp_setting')->insert($insertData);
        }


        return $this->renderSuccess([],'设置成功');

    }

    /**
     * 日志列表
     */
    public function log(){

        $wxapp_id = $this->getWxappId();

        $filter = [];

        $param = $this->request->param();
        // 起始时间
        !empty($param['start_time']) && $filter['create_time']  = ['>=',strtotime($param['start_time'])];
        // 截止时间
        !empty($param['end_time']) &&  $filter['create_time']  = ['<',strtotime($param['end_time']) + 86400];

        if(!empty($param['start_time']) && !empty($param['end_time'])){
            $filter['create_time']  = ['between',[strtotime($param['start_time']), strtotime($param['end_time']) + 86400]];
        }

        $list = db('setting_log')
            ->where(['type'=>1,'wxapp_id'=>$wxapp_id])
            ->where($filter)
            ->order(['create_time desc'])
            ->paginate(20, false, [
                'query' => \request()->request()
            ])->each(function($item,$key){
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                $item['values'] = json_decode($item['values'],true);
                $item['values']['start_time'] = date('Y-m-d H:i:s',$item['values']['start_time']);
                return $item;
            });


        return $this->renderSuccess($list,"查询成功");


    }




}